<template>
  <div class="task">
    <h2>{{ task.name }}</h2>

    <!-- 阅读材料 -->
    <div v-for="material in task.reading_materials" :key="material.id">
      <ReadingMaterialComponent :material="material" />
    </div>

    <!-- 单选题 -->
    <div v-for="question in task.single_choice_questions" :key="question.id">
      <SingleChoiceQuestionComponent
        :question="question"
        :answer="singleChoiceAnswers[question.id]"
        @update-answer="(ans) => updateSingleChoiceAnswer(question.id, ans)"
      />
    </div>

    <!-- 多选题 -->
    <div v-for="question in task.multiple_choice_questions" :key="question.id">
      <MultipleChoiceQuestionComponent
        :question="question"
        :answers="multipleChoiceAnswers[question.id] || []"
        @update-answers="(ans) => updateMultipleChoiceAnswer(question.id, ans)"
      />
    </div>

    <!-- 填空题 -->
    <div v-for="question in task.fill_in_blank_questions" :key="question.id">
      <FillInBlankQuestionComponent
        :question="question"
        :answer="fillInBlankAnswers[question.id]"
        @update-answer="(ans) => updateFillInBlankAnswer(question.id, ans)"
      />
    </div>

    <!-- 提交按钮 -->
    <el-button type="primary" @click="submitAnswers">提交答案</el-button>

    <!-- 显示评分结果 -->
    <div v-if="scoreInfo" class="score-display">
      <p>得分：{{ scoreInfo.total_score }} / {{ scoreInfo.max_score }}</p>
    </div>
  </div>
</template>

<script>
import ReadingMaterialComponent from './ReadingMaterialComponent.vue';
import SingleChoiceQuestionComponent from './SingleChoiceQuestionComponent.vue';
import MultipleChoiceQuestionComponent from './MultipleChoiceQuestionComponent.vue';
import FillInBlankQuestionComponent from './FillInBlankQuestionComponent.vue';

export default {
  name: 'TaskComponent',
  components: {
    ReadingMaterialComponent,
    SingleChoiceQuestionComponent,
    MultipleChoiceQuestionComponent,
    FillInBlankQuestionComponent
  },
  props: {
    task: {
      type: Object,
      required: true
    }
  },
 
  data() {
    return {
      singleChoiceAnswers: {}, // { questionId: answer }
      multipleChoiceAnswers: {}, // { questionId: ["A", "B"] }
      fillInBlankAnswers: {}, // { questionId: answer }
      scoreInfo: null, // 存储评分结果 { total_score: X, max_score: Y }
      isSubmitting: false, // 防止重复提交
      hasSubmitted: false, // 标记是否已提交，可以用来禁用题目或显示答案
      studentAnswerRecordId: null
    };
  },
  mounted() {
    this.fetchStudentAnswerRecord();
  },
  methods: {
    async fetchStudentAnswerRecord() {
      try {
        const res = await this.$axios.post('/api/student-answers/get-or-create-for-task/', {
          experiment_id: this.$route.params.experimentId, // 从路由获取实验ID
          task_id: this.task.id
        });
        
        this.studentAnswerRecordId = res.data.id;
        if (res.data.score !== undefined) {
          this.scoreInfo = {
            total_score: res.data.score,
            max_score: res.data.max_score || 3 // 默认最大值或从后端获取
          };
          this.hasSubmitted = true;
        }
        // 加载历史答案和成绩
        if (res.data.single_choice_answers) {
          this.singleChoiceAnswers = res.data.single_choice_answers;
        }
        if (res.data.multiple_choice_answers) {
          this.multipleChoiceAnswers = res.data.multiple_choice_answers;
        }
        if (res.data.fill_in_blank_answers) {
          this.fillInBlankAnswers = res.data.fill_in_blank_answers;
        }
        if (res.data.score !== undefined) {
          this.scoreInfo = {
            total_score: res.data.score,
            max_score: res.data.max_score
          };
          this.hasSubmitted = true;
        }
      console.log('答题记录返回：', res.data);
      } catch (error) {
        console.error('加载答题记录失败:', error);
        this.$message.error('加载历史答题记录失败');
      }
    },
    updateSingleChoiceAnswer(id, answer) {
      this.singleChoiceAnswers[id] = answer;
    },
    updateMultipleChoiceAnswer(id, answers) {
      this.multipleChoiceAnswers[id] = answers;
    },
    updateFillInBlankAnswer(id, answer) {
      this.fillInBlankAnswers[id] = answer;
    },

    async submitAnswers() {
      if (this.isSubmitting || this.hasSubmitted) {
        this.$message.warning(this.hasSubmitted ? '您已提交过答案！' : '正在提交中，请稍候...');
        return;
      }
      this.isSubmitting = true;

      const payload = {
        // task_id: this.task.id, // 后端可以通过 StudentAnswerRecord 的 task 字段获取
        answers: {
          single_choice: this.singleChoiceAnswers,
          multiple_choice: this.multipleChoiceAnswers,
          fill_in_blank: this.fillInBlankAnswers
        }
      };

      try {
        const recordPK = this.getStudentAnswerRecordPK();
        if (!recordPK) {
            this.$message.error('无法获取答题记录ID，请刷新页面或联系管理员。');
            this.isSubmitting = false;
            return;
        }
        // 调用后端接口保存答题记录并获取评分
        // URL 指向 StudentAnswerRecordViewSet 的 submit_answers action
        const response = await this.$axios.post(
          `/api/student-answers/${recordPK}/submit_answers/`, 
          payload
        );

        if (response.data && response.data.score) {
          this.scoreInfo = response.data.score; // 使用后端返回的评分结果
          this.$message.success('答案已提交，评测完成！');
          this.hasSubmitted = true; // 标记已提交
          // 可选: 你可以在这里触发一个事件，通知父组件任务已完成并附带分数
          // this.$emit('task-submitted', { taskId: this.task.id, score: this.scoreInfo });
        } else {
          this.$message.error('提交成功，但未能获取评分结果。');
          console.error('Unexpected response structure:', response.data);
        }
      } catch (error) {
        console.error('提交失败:', error.response || error);
        let errMsg = '提交失败，请重试';
        if (error.response && error.response.data) {
            // 尝试获取更详细的错误信息
            if (error.response.data.detail) errMsg = error.response.data.detail;
            else if (typeof error.response.data === 'string') errMsg = error.response.data;
            else if (error.response.data.error) errMsg = error.response.data.error;
        }
        this.$message.error(errMsg);
      } finally {
        this.isSubmitting = false;
      }
    },
    getStudentAnswerRecordPK() {
      // **重要**: 这个函数需要返回当前学生针对此任务的 StudentAnswerRecord 的主键 (PK)
      // 这个 PK 应该在学生开始任务时由后端创建并返回给前端，或者前端在进入任务页面时获取。
      // 1. 如果 TaskComponent 是在一个 Experiment 页面内，并且 Experiment 加载时
      //    后端为每个 task 创建了 StudentAnswerRecord，那么这个 ID 可以通过 prop 传入。
      // 2. 或者，此 TaskComponent 可能需要自己负责 get_or_create StudentAnswerRecord。
      //    这种情况下，submitAnswers 提交的 URL 可能不是 detail URL，
      //    而是像 /api/student-answers/submit_for_task/，并在 payload 中包含 task_id。
      //
      // 对于当前 `submit_answers` 是一个 detail_route (`@action(detail=True, methods=['post'])`)
      // 我们必须有一个 StudentAnswerRecord 的 PK.
      
      // 示例：如果 studentAnswerRecordId prop 被传递
      if (!this.studentAnswerRecordId) {
        this.$message.error('无法获取答题记录，请刷新页面重试');
        throw new Error('Missing studentAnswerRecordId');
      }
      return this.studentAnswerRecordId;

      // 应急/示例: 如果你的后端 StudentAnswerRecordViewSet 的 submit_answers
      // 不是 detail=True, 而是 detail=False, 并且它自己处理查找或创建记录,
      // 那么你就不需要这里的 PK，并且API URL也会不同。
      // 但根据你的 views.py，它是 detail=True，所以 PK 是必需的。
      // 仅为示例，这需要一个真实的 StudentAnswerRecord ID
    },

    getStudentAnswerRecordId() {
      // 示例：从 localStorage 获取学生实验记录 ID 或使用固定规则生成
      // 实际应根据后端设计动态获取或创建 StudentAnswerRecord
      return 1; // 示例 ID，需替换为真实值
    }
  }
};
</script>

<style scoped>
.task {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-bottom: 20px;
}

.score-display {
  margin-top: 15px;
  font-weight: bold;
  color: green;
}
</style>